package com.svs.framework.shiro.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import com.svs.common.utils.StringUtils;
import com.svs.common.utils.bean.BeanUtils;
import com.svs.framework.shiro.realm.UserRealm;
import com.svs.system.domain.SysUser;

/**
 * shiro 工具类
 * 
 * @author dujianqiao
 */
public class ShiroUtils { 
	public static Subject getSubjct() {
		return SecurityUtils.getSubject();
	}

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static void logout() {
		getSubjct().logout();
	}

	public static SysUser getSysUser() {
		SysUser user = null;
		Object obj = getSession().getAttribute(SysConstants.USER_SESSION);
		if (StringUtils.isNotNull(obj)) {
			user = new SysUser();
			BeanUtils.copyBeanProp(user, obj);
		}
		return user;
	}

	public static void setSysUser(SysUser user) {
		ShiroUtils.getSession().setAttribute(SysConstants.USER_SESSION, user);
	}

	public static void clearCachedAuthorizationInfo() {
		RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
		UserRealm realm = (UserRealm) rsm.getRealms().iterator().next();
		realm.clearCachedAuthorizationInfo();
	}

	public static Long getUserId() {
		return getSysUser().getUserId().longValue();
	}

	public static String getLoginName() {
		return getSysUser().getLoginName();
	}

	public static String getIp() {
		return getSubjct().getSession().getHost();
	}

	public static String getSessionId() {
		return String.valueOf(getSubjct().getSession().getId());
	}

	/**
	 * 生成随机盐
	 */
	public static String randomSalt() {
		// 一个Byte占两个字节，此处生成的3字节，字符串长度为6
		SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
		String hex = secureRandom.nextBytes(3).toHex();
		return hex;
	}
}
